import ast
from twisted.plugin import IPlugin
from dopplershift.core.plugins.interfaces import IDSPlugin
from zope.interface import implements
from dopplershift.core.containers.mediator import getMediator
from twisted.internet.defer import Deferred
from twisted.internet import reactor
import uuid
import time
def populate_vertical(out_list, x, y, max_y, with_central=True):
    if with_central:
        out_list.append((x,y))
    if max_y > y+1:
        out_list.append((x, y+1))
    if y-1 > -1:
        out_list.append((x, y-1))
    
def populate_neighbours(G, coords, max_x, max_y):
    left_x = coords[0] -1
    right_x = coords[0] + 1
    out = []
    populate_vertical(out, coords[0], coords[1], max_y, False)
    if left_x > -1:
        populate_vertical(out, left_x, coords[1], max_y)
    if right_x < max_x:
        populate_vertical(out, right_x, coords[1], max_y)
        
class DSAuthBackend(object):
    implements(IDSPlugin, IPlugin)
    application = 'backend.auth'
    name = 'default'
    
    
    def configure(self, config):
        '''
        '''
        getMediator().register('AuthBackend', self)
    def authenticate(self, uid):
        d = Deferred()
        self._authenticate(uid).addCallbacks(
                                                    self._authenticate_result, self._error,
                                                    callbackArgs=[uid, d], 
                                                    errbackArgs=[uid, d]
                                                    )
        
        return d
    def _authenticate(self, uid ):
        d = Deferred()
        reactor.callLater(1, d.callback, {})
        return d
    def _save(self, data, uid, login):
        '''
        '''
    def _delete(self, uid):
        '''
        '''
    def delete(self, uid):
        return self._delete(uid)
    def save(self, data, uid=None, login=None):
        '''
        '''
        deferObj = Deferred()
        if uid == None:
            uid = uuid.uuid5(uuid.NAMESPACE_OID, str("%s/%s"%(login, time.time()))).get_hex()
        d = self._save(data, uid, login)
        d.addCallback(self._authenticate_result, uid, deferObj)
        d.addErrback(self._error, uid, deferObj)
        return deferObj
    
    def _authenticate_result(self, result, passphrase, deferObj):
        '''
        '''
        deferObj.callback({"uid": passphrase, "session": result})
    def _error(self, err, passphrase, deferObj):
        '''
        '''
        deferObj.errback(err)